package com.jingdianjichi.redis.init;

import com.jingdianjichi.redis.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author rose
 */
@Component
@Slf4j
public class InitCache implements CommandLineRunner {

    /**
     * 项目启动时执行该方法
     * <p>
     * 缓存预热
     */
    @Override
    public void run(String... args) throws Exception {
        // 首先拿到哪些缓存需要进行一个预热
        ApplicationContext applicationContext = SpringContextUtil.getApplicationContext();
        Map<String, AbstractCache> beanMap = applicationContext.getBeansOfType(AbstractCache.class);
        // 调用init方法
        if (beanMap.isEmpty()) {
            return;
        }
        for (Map.Entry<String, AbstractCache> entry : beanMap.entrySet()) {
            log.info("初始化{}缓存：{}", entry.getKey(), entry.getValue());
            AbstractCache abstractCache = (AbstractCache) SpringContextUtil.getBean(entry.getValue().getClass());
            abstractCache.initCache();
        }
    }
}
